package com.turing.usdtpay.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.turing.usdtpay.R;
import com.turing.usdtpay.http.ApiService;
import com.turing.usdtpay.http.ApiUrl;
import com.turing.usdtpay.http.callback.ApiCallback;
import com.turing.usdtpay.http.entity.ResponseDate;
import com.turing.usdtpay.mvp.activity.RodOrderActivity;
import com.turing.usdtpay.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

/**
 * @作者：JAY
 * @创建时间：2019/10/22 10:06
 * @描述：
 **/
public class PushService extends Service {
    private static String TAG = "PushService";
    private Messenger messenger;
    private RobThread mRobThread;
    private boolean isRunning;
    private boolean needNotification = false;
    @Override
    public void onCreate() {
        super.onCreate();
        if (mRobThread == null){
            mRobThread = new RobThread();
            isRunning = true;
            mRobThread.start();
        }
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        messenger = (Messenger) intent.getParcelableExtra("msg");
        needNotification = intent.getBooleanExtra("push",false);
        LogUtils.d(TAG +" onStartCommand :"+needNotification+" thread :"+(mRobThread == null));
        return START_REDELIVER_INTENT;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 发送通知
     *
     * @param context
     */
    private void sendNotification(Context context) {
        NotificationManager manager = (NotificationManager) context.getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(context, RodOrderActivity.class);
        int pushid = (int) System.currentTimeMillis();
        PendingIntent pendingIntent = PendingIntent.getActivity(context, pushid, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "push");
        builder.setContentTitle("新订单消息");
        builder.setContentText("您有新的订单，请及时处理。");
        builder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
        builder.setAutoCancel(true);//点击通知后，状态栏是否自动删除通知。
        builder.setSmallIcon(R.mipmap.icon_logo);//设置小图标
        builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon_logo));
        builder.setWhen(System.currentTimeMillis());
        builder.setContentIntent(pendingIntent);
        builder.setChannelId("push");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("push", "test", NotificationManager.IMPORTANCE_HIGH);
            channel.enableLights(true);//闪光灯
            channel.enableVibration(true);//是否允许震动
            channel.setDescription("push");
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);//锁屏显示通知
            manager.createNotificationChannel(channel);
        }
        manager.notify(pushid, builder.build());

    }

    private void playSound(Context context) {
        Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.sound);
        MediaPlayer player = new MediaPlayer();
        try {
            player.setDataSource(context, uri);
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 抢买线程
     */
    class RobThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (isRunning) {
                HashMap<String, String> map = new HashMap<>();
                ApiService.getInstance().postRequestWithCommmon(PushService.this.getApplicationContext(), ApiUrl.API_GET_TRADE_STATE, map, new ApiCallback() {
                    @Override
                    public void onSuccess(int code, ResponseDate date) {
                        if (date.getRet() == 1) {
                            Message msg = new Message();
                            try {
                                JSONObject object = new JSONObject(date.getDate());
                                int cur_status = object.optInt("cur_status");
                                if (cur_status == 1) {
                                    msg.what = 1;
                                } else if (cur_status == 2) {
                                    msg.what = 2;
                                } else if (cur_status == 3) {
                                    msg.what = 3;
                                } else if (cur_status == 4) {
                                    msg.what = 4;
                                }else {
                                    msg.what = 0;
                                }
                                try {
                                    messenger.send(msg);
                                    if (cur_status == 2 || cur_status == 4) {
                                        if (needNotification){
                                            sendNotification(PushService.this);
                                            playSound(PushService.this);
                                            needNotification = false;
                                        }
                                    }

                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }else {
                            Log.e("turing","请求失败 -->"+date.toString());
                        }
                    }

                    @Override
                    public void onFailure(Throwable exception) {
                        Log.e("turing","请求失败 -->"+exception.getMessage());
                    }
                });
                try {
                    sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    LogUtils.d(TAG + "RobThread 发生中断");
                    return;
                }

            }

        }
    }

    @Override
    public void onDestroy() {
        isRunning = false;
        super.onDestroy();
    }
}
